﻿using AutoMapper;
using MediatR;
using T.S.BaseData.Api.AppClinet.Commend.Goods;
using T.S.BaseData.Domain.Entity;
using T.S.BaseData.ErrorCode;
using T.S.BaseData.Infrastructure.Base;

namespace T.S.BaseData.Api.AppClinet.CommendHand.Goods
{
    public class BasicinfoAddCommandHandle : IRequestHandler<BasicinfoAddCommand, ApiResult<int>>
    {

        private readonly IBaseRepository<BasicInfo> basicRepo;
        private readonly IMapper mapper;
        private readonly ILogger<BasicinfoAddCommandHandle> logger;

        public BasicinfoAddCommandHandle(IBaseRepository<BasicInfo> basicRepo, 
            IMapper mapper, 
            ILogger<BasicinfoAddCommandHandle> logger)
        {
            this.basicRepo = basicRepo;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(BasicinfoAddCommand request, CancellationToken cancellationToken)
        {
            var csRedis = new CSRedis.CSRedisClient("127.0.0.1:6379,dafaultDatabase=1,prefix=_My");
            var cachedData = await csRedis.GetAsync("Basic");

            csRedis.Del(cachedData);

            ApiResult<int> result = new ApiResult<int>();

            var model = mapper.Map<BasicInfo>(request);
            model.CreateTime = DateTime.Now;

            var r = basicRepo.Crate(model);
            if (r>0)
            {
                result.Code = ApiEnums.Success;
                result.Data = r;
                result.Meg = "添加商品基本信息成功";

                logger.LogInformation("添加商品基本信息成功");

                csRedis.Del(cachedData);
            }
            else
            {
                result.Code = ApiEnums.Error;
                result.Data = r;
                result.Meg = "添加商品基本信息失败";

                logger.LogInformation("添加商品基本信息失败");

                //csRedis.Del(cachedData);
            }

            return await Task.FromResult(result);
        }
    }
}
